package com.wxlalt.rediscache.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxlalt.rediscache.config.VersionCall;
import com.wxlalt.rediscache.entity.Result;
import com.wxlalt.rediscache.entity.Shop;
import com.wxlalt.rediscache.mapper.ShopMapper;
import com.wxlalt.rediscache.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * @author a1615
 */
@Service
@VersionCall.Version("v3")
public class ShopServiceImpl_v3 extends ServiceImpl<ShopMapper, Shop> implements IShopService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ShopServiceImpl_v1 shopServiceImpl_v1;

    public static final Long CACHE_SHOP_TTL = 30L;
    public static final Long CACHE_NULL_TTL = 10L;
    public static final String CACHE_SHOP_KEY = "cache:shop:";


    /**
     * 优化：查找一个不存在的key
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1.从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2.判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 3.存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        // 判断命中的是否是空值
        if (shopJson != null) {
            // 返回一个错误信息
            return Result.fail("店铺信息不存在！");
        }

        // 4.不存在，根据id查询数据库
        Shop shop = shopServiceImpl_v1.getById(id);
        // 5.不存在，返回错误
        if (shop == null) {
            // 将空值写入redis，空值的缓存时间应该小于正常值的时间
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            // 返回错误信息
            return Result.fail("店铺不存在！");
        }
        // 6.存在，写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 7.返回
        return Result.ok(shop);
    }

    @Override
    public Result update(Shop shop) {
        return null;
    }


}
